package com.ruicar.afs.cloud.afscase.processor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.*;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolHistoryService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.common.utils.Const;
import com.ruicar.afs.cloud.afscase.common.utils.DicUtils;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.*;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.processor.entity.WorkExceptionInfo;
import com.ruicar.afs.cloud.afscase.processor.enums.LoanSubmitEnum;
import com.ruicar.afs.cloud.afscase.processor.enums.NormalSubmitType;
import com.ruicar.afs.cloud.afscase.processor.service.LoanApproveWorkflowService;
import com.ruicar.afs.cloud.afscase.processor.service.WorkExceptionInfoService;
import com.ruicar.afs.cloud.afscase.processor.util.WorkflowTypeUtil;
import com.ruicar.afs.cloud.afscase.processor.vo.*;
import com.ruicar.afs.cloud.afscase.risk.entity.CaseTortoiseApply;
import com.ruicar.afs.cloud.afscase.risk.entity.CaseTortoiseFraudHand;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseApplyService;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseFraudHandService;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseService;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.common.core.enums.AfsBaseEnum;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import com.ruicar.afs.cloud.risk.api.enums.tortoise.GwtTortoiseAntiFraudCallStep;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.*;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author yk.Li
 * @Date 2020/7/17
 * @description
 */
@Service
@Slf4j
@AllArgsConstructor
public class LoanApproveWorkflowServiceImpl implements LoanApproveWorkflowService {
    private WorkflowService workflowService;
    private WorkProcessScheduleInfoService workProcessScheduleInfoService;
    private CaseContractInfoService caseContractInfoService;
    private CaseApproveRecordService caseApproveRecordService;
    private WorkTaskPoolService workTaskPoolService;
    private WorkTaskPoolHistoryService workTaskPoolHistoryService;
    private ApproveLoanInfoService approveLoanInfoService;
    private WorkExceptionInfoService workExceptionInfoService;
    private CaseBaseInfoService caseBaseInfoService;
    private CaseCostInfoService caseCostInfoService;
    private CaseChannelInfoService caseChannelInfoService;
    private CaseCarInfoService caseCarInfoService;
    private CaseCarStyleDetailService caseCarStyleDetailService;
    private CaseTortoiseApplyService caseTortoiseApplyService;
    private CaseTortoiseFraudHandService caseTortoiseFraudHandService;
    private CaseTortoiseService caseTortoiseService;

    @Override
    public WorkFlowResponse start(LoanWorkflowDataVO loanWorkflowDataVO) {
        WorkProcessScheduleInfoTemp temp = loanWorkflowDataVO.getWorkProcessScheduleInfoTemp();
        if(null != temp){
            StartFlowRequest request = new StartFlowRequest();
            request.setAfsFlowKey(temp.getAfsFlowKey());
            request.setBizDataId(Convert.toStr(temp.getId()));
            request.setFlowName(new StringBuffer(temp.getContractNo())
                    .append("-")
                    .append(WorkflowTypeUtil.getApproveTypeName(temp.getAfsFlowKey()))
                    .append("(")
                    .append(WorkflowTypeUtil.getType(temp.getAfsFlowKey()).getDesc())
                    .append(")").toString());
            WorkFlowResponse response = workflowService
                    .startWorkFlow(request, getBusinessData(loanWorkflowDataVO.getLoanBusinessDataVO()));
            if (Const.WORKFLOW_RESPONSE_SUCCESS == response.getSuccess()) {
                saveStartRecord(temp, caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo, temp.getContractNo())));
            }
            return response;
        }
        return null;
    }

    public void isNull(NormalTaskSubmitVO submitVO) {
        if (null != submitVO.getWorkFlowInfo() && null != submitVO.getRecord()) {
            submitVO.setWorkFlowInfo(workProcessScheduleInfoService.getById(submitVO.getRecord().getStageId()));
        }
        if (Objects.isNull(submitVO.getWorkTaskPool())) {
            WorkProcessScheduleInfo workFlowInfo = submitVO.getWorkFlowInfo();
            if (null != workFlowInfo) {
                if(submitVO.getAutoFlag()){
                    submitVO.setWorkTaskPool(workTaskPoolService.getOne(Wrappers.<WorkTaskPool>lambdaQuery()
                            .eq(WorkTaskPool::getStageId, workFlowInfo.getId().toString())
                            .eq(WorkTaskPool::getTaskNodeId, workFlowInfo.getCurrentNodeId())));
                }else {
                    submitVO.setWorkTaskPool(workTaskPoolService.getOne(Wrappers.<WorkTaskPool>lambdaQuery()
                            .eq(WorkTaskPool::getStageId, workFlowInfo.getId().toString())
                            .eq(WorkTaskPool::getTaskNodeId, workFlowInfo.getCurrentNodeId())
                            .eq(WorkTaskPool::getApproveStaff, SecurityUtils.getUser().getUsername())));
                }
            }
        }
    }

    @Transactional
    @Override
    public WorkFlowResponse submit(NormalTaskSubmitVO submitVO) {
        isNull(submitVO);
        LoanSubmitEnum loanSubmitEnum = (LoanSubmitEnum) AfsEnumUtil.getEnum(submitVO.getRecord().getApproveSuggest(), LoanSubmitEnum.class);
        switch (loanSubmitEnum) {
            case SUBMIT:
                submitLoan(submitVO);
                break;
            case BACK_PARTNERS:
                submitBackToPartners(submitVO);
                break;
            case BACK_AUDIT:
                submitBackAudit(submitVO);
                break;
            case BACK:
                submitBack(submitVO);
                break;
            case REPAIR_REPLY:
                submitRepairReply(submitVO);
                break;
            default:
                log.info("审批建议不存在:{}", loanSubmitEnum);
        }
        return null;
    }

    /**
     * @param reformistVO
     * @description 改派
     * @author yk.Li
     * @date 2020/7/17
     * @updateBy rongji.zhang
     * @updateDate 2020/8/21
     */
    @Override
    public WorkFlowResponse reformist(NormalReformistVO reformistVO) {
        WorkProcessScheduleInfo info = workProcessScheduleInfoService.getById(reformistVO.getStageId());
        afterTaskHandlerChange(info, reformistVO);
        TaskReformistRequest reformistRequest = new TaskReformistRequest();
        reformistRequest.setAfsFlowKey(info.getAfsFlowKey());
        reformistRequest.setBizDataId(Convert.toStr(info.getId()));
        reformistRequest.setFlowInstanceId(info.getStageId());
        reformistRequest.setUserName(reformistVO.getReformistUserName());
        reformistRequest.setUserRealName(reformistVO.getReformistUserRealName());
        WorkFlowResponse response = workflowService.taskReformist(reformistRequest, getBusinessData(info.getApplyNo()));
        if (Const.WORKFLOW_RESPONSE_SUCCESS == response.getSuccess()) {
            return response;
        } else {
            throw new AfsBaseException(response.getCode(), response.getMessage());
        }
    }

    /**
     * @Description 任务改派后删除当前任务数据
     * @Author rongji.zhang
     * @Date 2020/8/20 18:28
     */
    @Transactional(rollbackFor = Exception.class)
    public void afterTaskHandlerChange(WorkProcessScheduleInfo info, NormalReformistVO reformistVO) {
        WorkTaskPool pool = workTaskPoolService.getOne(Wrappers.<WorkTaskPool>lambdaQuery()
                .eq(WorkTaskPool::getStageId, info.getId().toString())
                .eq(WorkTaskPool::getApproveStaff, reformistVO.getOriUserName()));
        workTaskPoolService.removeById(pool.getId());
        // 保存操作日志
        CaseApproveRecord record = caseApproveRecordService.getOne(Wrappers.<CaseApproveRecord>lambdaQuery()
                .eq(CaseApproveRecord::getTaskId,pool.getId().toString())
                .eq(StringUtils.isNotBlank(pool.getContractNo()),CaseApproveRecord::getContractNo,pool.getContractNo()),false);
        record.setApproveEndTime(new Date());
        record.setApproveSuggest(AfsEnumUtil.key(NormalSubmitType.REFORMIST));
        record.setApproveSuggestName(AfsEnumUtil.desc(NormalSubmitType.REFORMIST));
        StringBuffer approveRemark = new StringBuffer(SecurityUtils.getUser().getUserRealName()).append("改派至").append(reformistVO.getReformistUserRealName()).append(" ");
        if (StrUtil.isNotBlank(pool.getRemainData())) {
            JSONObject json = JSONObject.parseObject(pool.getRemainData());
            if (json.containsKey(AfsEnumUtil.key(RemainKeyEnum.RECORD))) {
                CaseApproveRecord remindRecord = json.getObject(AfsEnumUtil.key(RemainKeyEnum.RECORD), CaseApproveRecord.class);
                if (StrUtil.isNotBlank(remindRecord.getApproveSuggest())) {
                    Map<String, List<DicDataDto>> suggestDicMap = DicHelper.getDicMaps("approveSuggest");
                    approveRemark.append(DicUtils.translate(remindRecord.getApproveSuggest(), suggestDicMap));
                    if (StrUtil.isNotBlank(remindRecord.getApproveReason())) {
                        String[] reasons = remindRecord.getApproveReason()
                                .replace("[", "")
                                .replace("]", "")
                                .split(",");
                        Map<String, List<DicDataDto>> reasonDicMap = DicHelper.getDicMaps(remindRecord.getApproveSuggest());
                        for (String reason : reasons) {
                            approveRemark.append("【")
                                    .append(DicUtils.translate(reason, reasonDicMap))
                                    .append("】,");
                        }
                    }
                }
                if (StrUtil.isNotBlank(remindRecord.getApproveRemark())) {
                    approveRemark.append(remindRecord.getApproveRemark());
                }
            }
        }
        CaseContractInfo contractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo,pool.getContractNo()));
        record.setFlowNode(contractInfo.getFlowNode());
        record.setApproveMessage(approveRemark.toString());
        record.setApproveRemark(approveRemark.toString());
        caseApproveRecordService.updateById(record);
        delOldAndNewPoolHistory(NormalTaskSubmitVO.builder().workFlowInfo(info).record(record).workTaskPool(pool).autoFlag(false).build());
    }


    /**
     * 结束流程
     *
     * @param fLowGiveUpRequest
     * @return
     */
    @Override
    public WorkFlowResponse flowGiveUp(FLowGiveUpRequest fLowGiveUpRequest) {
        WorkFlowResponse response = workflowService.flowGiveUp(fLowGiveUpRequest);
        Assert.isTrue(Const.WORKFLOW_RESPONSE_SUCCESS == response.getSuccess(), response.getMessage());
        return response;
    }

    /**
     * 流程异常处理
     * @param id
     * @return
     */
    @Override
    public void resumeFlow(Long id) {
        WorkExceptionInfo workExceptionInfo = workExceptionInfoService.getById(id);
        WorkFlowResponse response = workflowService.resumeFlow(workExceptionInfo.getFlowParseId().toString(),workExceptionInfo.getFlowParseExceptionId());
        /**异常处理之后会走分单方法会自动修改合同数据 change by fansgchenliang*/
        if (!(Const.WORKFLOW_RESPONSE_SUCCESS == response.getSuccess())) {
            log.warn("流程恢复失败，WorkPool_stageId:{},exceptionId:{}.message:{}",workExceptionInfo.getFlowParseId(),workExceptionInfo.getFlowParseExceptionId(),response.getMessage());
        }
    }

    /**
     * @param
     * @description 保存流程发起日志
     * @author yk.Li
     * @date 2020/7/17
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveStartRecord(WorkProcessScheduleInfoTemp infoTemp, CaseContractInfo caseContractInfo) {
        CaseApproveRecord record = new CaseApproveRecord();
        record.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        record.setDisposeNodeName("开始节点");
        record.setDisposeStaff("自动处理");
        record.setStageId(Convert.toStr(infoTemp.getId()));
        record.setContractNo(caseContractInfo.getContractNo());
        record.setApplyNo(infoTemp.getApplyNo());
        record.setApproveSuggestName("发起放款流程");
        record.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        record.setCurrentPosition(CurrentPositionEnum.GENERAL_LOAN);
        record.setApproveStartTime(infoTemp.getStartTime());
        record.setApproveEndTime(infoTemp.getStartTime());
        caseApproveRecordService.save(record);

        /**保存合同信息表 更新案件状态*/
        caseContractInfo.setContractStatus(ContractStatusEnum.approve);
        //change by fangchenliang分配到人之后才变更为放款审核
        caseContractInfo.setBusinessStage(BusinessStageEnum.LOAN_APPROVAL.getCode());
        /**更新合同状态为分配中*/
        caseContractInfo.setApplyStatus(ApplyStatusEnum.ASSIGNING.getState());
        caseContractInfoService.updateById(caseContractInfo);
    }

    /**
     * 放款审核提交
     *
     * @param submitVO
     * @author yk.Li
     * @date 2020/6/29
     */
    private void submitLoan(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.SUBMIT, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * @param
     * @description 放款审核退回
     * @author yk.Li
     * @date 2020/7/3
     */
    private void submitBack(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.BACK, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * @param
     * @description 退回审核
     * @author yk.Li
     * @date 2020/7/1
     */
    private void submitBackAudit(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.BACK_AUDIT, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * @param
     * @description 补件回复
     * @author yk.Li
     * @date 2020/7/3
     */
    private void submitRepairReply(NormalTaskSubmitVO submitVO) {
        CaseApproveRecord record=changeCaseStatusAndSaveRecord(submitVO);
        //workTaskPoolService.removeById(submitVO.getWorkTaskPool().getId());
        //补件回复保存日志
        saveRepairReplyRecord(record,submitVO);
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.REPAIR_REPLY, submitVO);
        afterSubmit(resp);
    }

    /**
     * @Description 补充日志
     * @Author yk.Li
     * @Date 2020/08/11
     */
    private void saveRepairReplyRecord(CaseApproveRecord record,NormalTaskSubmitVO submitVO) {
        record.setApproveSuggest(AfsEnumUtil.key(LoanSubmitEnum.REPAIR_REPLY));
        record.setApproveSuggestName(AfsEnumUtil.desc(LoanSubmitEnum.REPAIR_REPLY));
        record.setApproveEndTime(new Date());
        record.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        record.setFlowNode(FlowNodeEnum.CHANNEL.getCode());
        caseApproveRecordService.updateById(record);
    }

    /**
     * @param submitVO
     * @description 退回合作商逻辑处理
     * @author yk.Li
     * @date 2020/6/29
     */
    private void submitBackToPartners(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.BACK_PARTNERS, submitVO);
        //提交成功
        afterSubmit(resp);
        //退回合作商信息通知进件系统
       approveLoanInfoService.backToPartnersNotic(submitVO.getRecord().getContractNo()
                , submitVO.getWorkFlowInfo().getStageId(),submitVO.getWorkTaskPool().getId().toString());
    }

    /**
     * @param
     * @description 提交成功修改数据
     * @author yk.Li
     * @date 2020/7/3
     */
    public void afterSubmit(WorkFlowResponse resp) {
        Assert.isTrue(Const.WORKFLOW_RESPONSE_SUCCESS == resp.getSuccess(), resp.getMessage());
    }

    /**
     * @param
     * @description 更改案件状态，保存日志
     * @author yk.Li
     * @date 2020/7/3
     */
    @Transactional(rollbackFor = Exception.class)
    public CaseApproveRecord changeCaseStatusAndSaveRecord(NormalTaskSubmitVO submitVO) {
        //删除当前任务，存入历史任务表
        this.delOldAndNewPoolHistory(submitVO);
        //保存日志
        CaseApproveRecord record=this.saveRecord(submitVO ,CurrentPositionEnum.GENERAL_LOAN);
        return record;
    }

    /**
     * @param
     * @description 删除当前任务，存入历史任务表
     * @author yk.Li
     * @date 2020/7/29
     */
    public void delOldAndNewPoolHistory(NormalTaskSubmitVO submitVO) {
        WorkTaskPoolHistory taskPoolHistory = new WorkTaskPoolHistory();
        if (submitVO.getAutoFlag()) {
            taskPoolHistory = workTaskPoolHistoryService.getOne(Wrappers.<WorkTaskPoolHistory>lambdaQuery()
                    .eq(WorkTaskPoolHistory::getStageId, submitVO.getRecord().getStageId())
                    .eq(WorkTaskPoolHistory::getTaskNodeId, submitVO.getWorkFlowInfo().getCurrentNodeId()));
        } else {
            AfsUser user = SecurityUtils.getUser();
            if(!ObjectUtils.isEmpty(user)) {
                taskPoolHistory = workTaskPoolHistoryService.getOne(Wrappers.<WorkTaskPoolHistory>lambdaQuery()
                        .eq(WorkTaskPoolHistory::getStageId, submitVO.getRecord().getStageId())
                        .eq(WorkTaskPoolHistory::getTaskNodeId, submitVO.getWorkFlowInfo().getCurrentNodeId())
                        .eq(WorkTaskPoolHistory::getApproveStaff, user.getId()));
            }
        }

        if (!ObjectUtils.isEmpty(taskPoolHistory)) {
            workTaskPoolHistoryService.removeById(taskPoolHistory);
        }
        WorkTaskPoolHistory currentPoolHistory = new WorkTaskPoolHistory();
        WorkTaskPool taskPool = submitVO.getWorkTaskPool();
        String[] ignoreFieldNames = new String[]{"id", "createBy", "createTime", "delFlag"};
        taskPool.setEndTime(new Date());
        taskPool.setApproveSuggest(submitVO.getRecord().getApproveSuggest());
        BeanUtil.copyProperties(taskPool, currentPoolHistory, ignoreFieldNames);

        List<WorkTaskPool> currentNodeTask =
                workTaskPoolService.list(Wrappers.<WorkTaskPool>lambdaQuery()
                        .eq(WorkTaskPool::getStageId, taskPool.getStageId())
                        .eq(WorkTaskPool::getTaskNodeId, taskPool.getTaskNodeId()));
        List<Long> ids = new ArrayList<>(currentNodeTask.size());
        currentNodeTask.forEach(task -> ids.add(task.getId()));

        workTaskPoolService.removeByIds(ids);
        workTaskPoolHistoryService.save(currentPoolHistory);
    }

    /**
     * @param
     * @description 保存流程操作日志
     * @author yk.Li
     * @date 2020/7/29
     */
    public CaseApproveRecord saveRecord(NormalTaskSubmitVO submitVO ,CurrentPositionEnum currentPositionEnum) {
        WorkTaskPool taskPool = submitVO.getWorkTaskPool();
        CaseApproveRecord record = submitVO.getRecord();
        record.setApproveEndTime(taskPool.getEndTime());
        record.setCurrentPosition(currentPositionEnum);
        caseApproveRecordService.updateById(record);
        return record;
    }

    /**
     * @param
     * @description 工作流推进
     * @author yk.Li
     * @date 2020/7/17
     */
    public WorkFlowResponse pushWorkflow(Enum<? extends AfsBaseEnum> submitButtonEnum, NormalTaskSubmitVO submitVO) {
        TaskSubmitRequest submitRequest = getTaskSubmitRequest(submitButtonEnum, submitVO);
        return workflowService.taskSubmit(submitRequest, getBusinessData(submitVO.getLoanBusinessDataVO()));
    }

    public TaskSubmitRequest getTaskSubmitRequest(Enum<? extends AfsBaseEnum> submitButtonEnum, NormalTaskSubmitVO submitVO) {
        QueryFLowCmdRequest cmdQueryRequest = new QueryFLowCmdRequest();
        cmdQueryRequest.setFlowInstanceId(submitVO.getWorkFlowInfo().getStageId());
        WorkFlowResponse<List<FlowCmdBean>> flowCmdResp = workflowService.queryFlowCmd(cmdQueryRequest);
        Assert.isTrue(Const.WORKFLOW_RESPONSE_SUCCESS == flowCmdResp.getSuccess(), flowCmdResp.getMessage());
        Assert.isTrue(CollectionUtil.isNotEmpty(flowCmdResp.getAfsData()), "无法获取到当前节点可操作命令");
        TaskSubmitRequest submitRequest = new TaskSubmitRequest();
        List<FlowCmdBean> cmdBeanList = flowCmdResp.getAfsData();

        WorkTaskPool taskPool = submitVO.getWorkTaskPool();
        String cmdName = AfsEnumUtil.desc(submitButtonEnum);
        for (FlowCmdBean flowCmdBean : cmdBeanList) {
            if (StrUtil.equals(flowCmdBean.getCmdDis(), cmdName)) {
                submitRequest.setAfsFlowKey(submitVO.getWorkFlowInfo().getAfsFlowKey());
                submitRequest.setBizDataId(taskPool.getStageId());
                submitRequest.setCmdId(flowCmdBean.getId());
                submitRequest.setGwtUserId(taskPool.getWorkflowDisposeId());
                break;
            }
        }
        Assert.isTrue(StrUtil.isNotBlank(submitRequest.getGwtUserId()), "当前节点未知的提交命令：" + cmdName);
        return submitRequest;
    }

    /**
     * @Description 业务数据获取
     * @Author rongji.zhang
     * @Date 2020/8/27 18:24
     */
    public JSONObject getBusinessData(String applyNo) {
        // 基本信息
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(
                Wrappers.<CaseBaseInfo>lambdaQuery().eq(CaseBaseInfo::getApplyNo, applyNo)
        );
        // 车款费用信息
        FinCostDetails finCostInfoCar = caseCostInfoService.list(
                Wrappers.<FinCostDetails>lambdaQuery().eq(FinCostDetails::getApplyNo, applyNo)
                        .eq(FinCostDetails::getCostType, CostTypeEnum.CARAMT.getCode())
        ).stream().findFirst().orElse(new FinCostDetails());

        // 附加贷费用信息
        FinCostDetails finCostInfoAppend = caseCostInfoService.list(
                Wrappers.<FinCostDetails>lambdaQuery().eq(FinCostDetails::getApplyNo, applyNo)
                        .eq(FinCostDetails::getCostType, CostTypeEnum.AFFIXAMT.getCode())
        ).stream().findFirst().orElse(new FinCostDetails());

        // 渠道信息
        CaseChannelInfo channelInfo = caseChannelInfoService.list(
                Wrappers.<CaseChannelInfo>lambdaQuery().eq(CaseChannelInfo::getApplyNo, applyNo)
        ).stream().findFirst().orElse(new CaseChannelInfo());

        // 车辆信息
        CaseCarInfo caseCarInfo = caseCarInfoService.list(
                Wrappers.<CaseCarInfo>lambdaQuery().eq(CaseCarInfo::getApplyNo, applyNo)
        ).stream().findFirst().orElse(new CaseCarInfo());

        // 车辆详情信息
        CaseCarStyleDetail carStyleDetailInfo = caseCarStyleDetailService.list(
                Wrappers.<CaseCarStyleDetail>lambdaQuery().eq(CaseCarStyleDetail::getCarId, caseCarInfo.getId())
        ).stream().findFirst().orElse(new CaseCarStyleDetail());

        CaseTortoiseApply caseTortoiseApply = caseTortoiseApplyService.list(
                Wrappers.<CaseTortoiseApply>lambdaQuery()
                        .eq(CaseTortoiseApply::getApplyNo,applyNo)
                        .orderByDesc(CaseTortoiseApply::getOperateDate)
        ).stream().findFirst().orElse(new CaseTortoiseApply());

        CaseTortoiseFraudHand fraudHand = caseTortoiseFraudHandService.list(
                Wrappers.<CaseTortoiseFraudHand>lambdaQuery()
                        .eq(CaseTortoiseFraudHand::getApplyNo,applyNo)
                        .orderByDesc(CaseTortoiseFraudHand::getOperateDate)
        ).stream().findFirst().orElse(new CaseTortoiseFraudHand());

        // TODO 取值待调整
        NormalBusinessDataVO businessDataVO = NormalBusinessDataVO.builder()
                .loanAmountAddUp(caseBaseInfo.getTotalLoanAmt())
                .businessType(caseBaseInfo.getBusinessType())
                .decisionValue(caseTortoiseApply.getDecisionResult())//决策引擎返回值
                .XuanWuGrade(caseTortoiseApply.getScore())//玄武评分
                .dealerQualityGrade("")//经销商优质等级
                .turningMark("")
                .conditionMark(caseBaseInfo.getConditionMark())
                .assigned("")//是否指定处理人
                .carType(Convert.toStr(caseBaseInfo.getCarType()))
                .carNature(Convert.toStr(caseBaseInfo.getCarNature()))
                .operateWay(Convert.toStr(caseBaseInfo.getOperateWay(), ""))
                .affiliatedWay(caseBaseInfo.getAffiliatedWay())
                .qualityGrade("")//优质等级
                .newEnergy(carStyleDetailInfo.getIsGreen())
                .channelBelong("")//渠道归属
                .appendLoanAmount(finCostInfoAppend.getLoanAmt())
                .carLevel(caseCarInfo.getCarBodyClass())
                .assetsClass(carStyleDetailInfo.getCarType())
                .carTypeDetail(carStyleDetailInfo.getCarTypeDetail())
                .dealerName(channelInfo.getDealerName())
                .antiFraudGrade(fraudHand.getFraudScore())//反欺诈评分
                .decisionGrade(caseTortoiseApply.getScoreLevel())//决策引擎评级
                .loanAmount(finCostInfoCar.getLoanAmt())
                .carDownPayScale(finCostInfoCar.getDownPayScale())
                .carLoanAmount(finCostInfoCar.getLoanAmt())
                .carDiscountAmount(Convert.toBigDecimal(finCostInfoCar.getDiscountAmt()))
                .carFinalPayment(finCostInfoCar.getTailPayAmt())
                .carRepayType(finCostInfoCar.getAlgorithmType())
                .appendDownPayScale(finCostInfoAppend.getDownPayScale())
                .appendLoanAmount(finCostInfoAppend.getLoanAmt())
                .appendDiscountAmount(finCostInfoAppend.getDiscountAmt())
                .appendFinalPayment(finCostInfoAppend.getTailPayAmt())
                .remoteSign(caseBaseInfo.getAutomaticTag())
                .build();
        return JSONObject.parseObject(JSONObject.toJSONString(businessDataVO));
    }

    /**
     * @param
     * @description 获取流程参数
     * @author yk.Li
     * @date 2020/7/17
     */
    public JSONObject getBusinessData(LoanBusinessDataVO loanBusinessDataVO) {
        if(null != loanBusinessDataVO){
            return JSONObject.parseObject(JSONObject.toJSONString(loanBusinessDataVO));
        }
        return new JSONObject();
    }
}
